﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class UserDeptController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly AdminUserDeptService _AdminUserDeptService;
        private readonly AdminUserGroupService _adminUserGroupService;
        private readonly LogService _logService;
        public UserDeptController(LoginUtil LoginUtil, AdminUserDeptService adminUserDeptService, AdminUserGroupService adminUserGroupService, LogService logService)
        {
            _LoginUtil = LoginUtil;
            _AdminUserDeptService = adminUserDeptService;
            _adminUserGroupService = adminUserGroupService;
            _logService = logService;
        }


        /// <summary>
        /// 输出JSON 树形栏目列表 内容管理的菜单列表使用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Index)]
        public async Task<IActionResult> GetTree()
        {
            var all = await _AdminUserDeptService.GetAllAsync();
            List<ViewAdminUserDept> treeModels = new();
            AdminUserDeptExtensions.IndentedCate(all, treeModels);
            return Json(treeModels);
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Index)]
        public async Task<IActionResult> IndexAsync(int json = 0)
        {
            if (json == 1)
            {
                var pagedList = await _AdminUserDeptService.GetAdminUserDepts();
                return Json(new { code = 0, data = pagedList });
            }
            return View();
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_AddOrEdit)]
        public async Task<IActionResult> AddOrEditAsync(int id, int edit = 0, int pid = 0)
        {
            if (edit == 1)
            {
                var data = await _AdminUserDeptService.GetInfo(id);
                return Json(new { status = 1, data });
            }
            ViewBag.userDepts = await _AdminUserDeptService.GetUserDeptListAsync();
            ViewBag.id = id;
            ViewBag.pid = pid;
            return View();

        }


        [HttpPost]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_AddOrEdit)]
        [Log(Name = "新增部门")]
        public async Task<IActionResult> CreatePostAsync(AdminUserDept cateModel)
        {
            if (ModelState.IsValid)
            {
                cateModel.GreatTime = DateTime.Now;
                object insertPri = await _AdminUserDeptService.InsertAsync(cateModel);
                return Json(new { status = 1, msg = "新增部门 ID:" + insertPri.ToString() });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }


        [HttpPost, ActionName("EditPost")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_AddOrEdit)]
        [Log(Name = "修改部门")]
        public async Task<IActionResult> EditPostAsync(EditAdminUserDept editModel, int id, int dyEdit = 0)
        {

            if (ModelState.IsValid)
            {
                AdminUserDept adminUserDept = await _AdminUserDeptService.GetInfo(id);
                if (dyEdit == 1)
                {

                    adminUserDept.OrderNum = editModel.OrderNum;

                    if (0 < await _AdminUserDeptService.UpdateAsync(adminUserDept))
                        return Json(new { status = 1, msg = "修改部门排序:" + adminUserDept.DeptName + " Id： " + id });
                    else
                        return Json(new { status = 0, msg = "修改部门失败:" + adminUserDept.DeptName + " Id： " + id });

                }

                adminUserDept.Pid = editModel.Pid;
                adminUserDept.DeptName = editModel.DeptName;
                adminUserDept.OrderNum = editModel.OrderNum;
                adminUserDept.Remark = editModel.Remark;
                if (0 < await _AdminUserDeptService.UpdateAsync(adminUserDept))
                    return Json(new { status = 1, msg = "修改部门:" + adminUserDept.DeptName + " Id： " + id });
                else
                    return Json(new { status = 0, msg = "修改部门:" + adminUserDept.DeptName + " Id： " + id });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        [HttpPost, ActionName("Delete")]
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Delete)]
        [Log(Name = "删除部门")]
        public async Task<IActionResult> DeleteAsync(int id)
        {
            if (await _AdminUserDeptService.DeleteByPriKeyAsync(id) > 0)
                return Json(new { status = 1, msg = "删除部门,Id： " + id });

            return Json(new { status = 0, msg = "删除失败！当前部门下有用户！" });
        }

        /// <summary>
        /// 修改工作类别资源管理
        /// </summary>

        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Resource)]
        public async Task<IActionResult> EditArticleCate(int id)
        {
            var data = await _AdminUserDeptService.GetInfo(id);
            AdminUserDeptCateRole adminUserDept = new()
            {
                Id = data.Id,
                ArticleCateRole = data.ArticleCateRole,
                DeptName = data.DeptName,
            };
            try
            {
                string[] str = JsonSerializer.Deserialize<string[]>(adminUserDept.ArticleCateRole);
                ViewBag.ArticleCateRole = string.Join(",", str);
            }
            catch (Exception)
            {

            }

            ViewBag.info = adminUserDept;
            return View();
        }

        [HttpPost]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Resource)]
        [Log(Name = "工作类别资源")]
        public async Task<IActionResult> ArticleCateEdit(AdminUserDeptCateRole adminUserGroup)
        {
            if (0 < await _AdminUserDeptService.UpdateAdminUserDeptCateRoleAsync(adminUserGroup))
                return Json(new { status = 1, msg = "修改部门工作类别权限 ID：" + adminUserGroup.Id });

            return Json(new { status = 0, msg = "修改部门工作类别权限 ID：" + adminUserGroup.Id });
        }


        /// <summary>
        /// 修改网站栏目
        /// </summary>

        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Resource)]
        public async Task<IActionResult> EditContentCate(int id)
        {
            var data = await _AdminUserDeptService.GetInfo(id);
            AdminUserDeptCateRole adminUserDept = new()
            {
                Id = data.Id,
                ContentCateRole = data.ContentCateRole,
                DeptName = data.DeptName,
            };
            try
            {
                string[] str = JsonSerializer.Deserialize<string[]>(adminUserDept.ContentCateRole);
                ViewBag.ContentCateRole = string.Join(",", str);
            }
            catch (Exception)
            {

            }

            ViewBag.info = adminUserDept;
            return View();
        }

        [HttpPost]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Resource)]
        [Log(Name = "网站栏目资源")]
        public async Task<IActionResult> ContentCateEdit(AdminUserDeptCateRole adminUserGroup)
        {
            if (0 < await _AdminUserDeptService.UpdateAdminUserDeptCateRoleAsync(adminUserGroup))
                return Json(new { status = 1, msg = "修改部门网站栏目权限 ID：" + adminUserGroup.Id });

            return Json(new { status = 0, msg = "修改部门网站栏目权限 ID：" + adminUserGroup.Id });
        }
    }
}
